# Planetfall Event Manager

from CvPythonExtensions import *
import sys
import Popup as PyPopup
import pickle
import CvEventManager
from CvScreenEnums import *
from PyHelpers import *
import CvUtil
import CvAdvisorUtils
import PyHelpers
import CustomFunctions
import OOSLogger

# globals
cf = CustomFunctions.CustomFunctions()
gc = CyGlobalContext()
localText = CyTranslator()
PyPlayer = PyHelpers.PyPlayer
PyInfo = PyHelpers.PyInfo

DefaultUnitAI = UnitAITypes.NO_UNITAI

class CvEventManagerPlanetfall(CvEventManager.CvEventManager):

	def __init__(self):	
		self.parent = CvEventManager.CvEventManager
		self.parent.__init__(self)
		
		self.reset()
		
	def onKbdEvent(self, argsList):
		self.parent.onKbdEvent(self, argsList)
		'keypress handler - return 1 if the event was consumed'

		eventType,key,mx,my,px,py = argsList
		game = gc.getGame()
		
		if ( eventType == self.EventKeyDown ):
			theKey=int(key)
			
			if (theKey == int(InputTypes.KB_X)):
				if ( self.bShift and self.bCtrl):
					if( game.getAIAutoPlay() > 0 ) :
						game.setAIAutoPlay( 0 )
					else :
						game.setAIAutoPlay( 100 )
					
			
		
		
	def onLoadGame(self, argsList):
		self.parent.onLoadGame(self, argsList)
		self.reset()
		return 0
		
	def onGameStart(self, argsList):
		'Called at the start of the game'
		self.parent.onGameStart(self, argsList)
		self.reset()

	def onBeginGameTurn(self, argsList):
		'Called at the beginning of the end of each turn'
		self.parent.onBeginGameTurn(self, argsList)
		iGameTurn = argsList[0]

	def onBeginPlayerTurn(self, argsList):
		'Called at the beginning of a players turn'
		self.parent.onBeginPlayerTurn(self, argsList)
		iGameTurn, iPlayer = argsList

		pPlayer = gc.getPlayer(iPlayer)
		eTeam = gc.getTeam(pPlayer.getTeam())
		iSpawningSpot = gc.getInfoTypeForString('IMPROVEMENT_SPAWNING_SPOT')
		iSpawningSpotSea = gc.getInfoTypeForString('IMPROVEMENT_SPAWNING_SPOT_SEA')
		iFungalTower = CvUtil.findInfoTypeNum(gc.getUnitInfo,gc.getNumUnitInfos(),'UNIT_FUNGAL_TOWER')
		iSporeLauncher = CvUtil.findInfoTypeNum(gc.getUnitInfo,gc.getNumUnitInfos(),'UNIT_SPORE_LAUNCHER')
		iFormer = gc.getInfoTypeForString('UNIT_FORMER')
		iDamagedFormer = gc.getInfoTypeForString('UNIT_FORMER_DAMAGED')
		iAquaformer = gc.getInfoTypeForString('UNIT_AQUAFORMER')
		iDamagedAquaformer = gc.getInfoTypeForString('UNIT_AQUAFORMER_DAMAGED')

		for pUnit in PyPlayer(iPlayer).getUnitList():
			if iPlayer == gc.getBARBARIAN_PLAYER():
				pPlot = pUnit.plot()
				if pUnit.getUnitType() == iSporeLauncher and pPlot.getNumUnits() == 1:
					if pPlot.getImprovementType() == gc.getInfoTypeForString('IMPROVEMENT_GOODY_HUT'):
						newUnit = pPlayer.initUnit(iFungalTower, pPlot.getX(), pPlot.getY(), UnitAITypes.NO_UNITAI, DirectionTypes.DIRECTION_NORTH)
						newUnit.convert(pUnit)
						pUnit.kill(false, PlayerTypes.NO_PLAYER)
				if pUnit.getUnitType() == iFungalTower:
					if pPlot.getImprovementType() == -1:
						if pPlot.isWater():
							pPlot.setImprovementType(iSpawningSpotSea)
						else:
							pPlot.setImprovementType(iSpawningSpot)
			if pUnit.getUnitType() == iDamagedFormer:
				iChance = gc.getGameSpeedInfo(gc.getGame().getGameSpeedType()).getTrainPercent()
				if 20 > CyGame().getSorenRandNum(iChance, "Maniac"):
					pPlot = pUnit.plot()
					newUnit = pPlayer.initUnit(iFormer, pPlot.getX(), pPlot.getY(), UnitAITypes.UNITAI_WORKER, DirectionTypes.DIRECTION_NORTH)
					pUnit.kill(false, PlayerTypes.NO_PLAYER)
			if pUnit.getUnitType() == iDamagedAquaformer:
				iChance = gc.getGameSpeedInfo(gc.getGame().getGameSpeedType()).getTrainPercent()
				if 20 > CyGame().getSorenRandNum(iChance, "Maniac"):
					pPlot = pUnit.plot()
					newUnit = pPlayer.initUnit(iAquaformer, pPlot.getX(), pPlot.getY(), UnitAITypes.UNITAI_WORKER_SEA, DirectionTypes.DIRECTION_NORTH)
					pUnit.kill(false, PlayerTypes.NO_PLAYER)
					
		#pPlayer = gc.getPlayer(iPlayer)
		#if pPlayer.isHuman():
		#	CyInterface().playGeneralSound("AS2D_TURN_COMPLETE")

	def onEndPlayerTurn(self, argsList):
		'Called at the end of a players turn'
		self.parent.onEndPlayerTurn(self, argsList)
		iGameTurn, iPlayer = argsList

		#pPlayer = gc.getPlayer(iPlayer)
		#if pPlayer.isHuman():
		#	CyInterface().playGeneralSound("AS2D_TURN_COMPLETE")
	
	def onEndTurnReady(self, iGameTurn):
		self.parent.onEndTurnReady(self, argsList)
		iGameTurn = argsList[0]

	def onCombatResult(self, argsList):
		'Combat Result'
		self.parent.onCombatResult(self, argsList)
		pWinner,pLoser = argsList
		playerX = PyPlayer(pWinner.getOwner())
		unitX = PyInfo.UnitInfo(pWinner.getUnitType())
		playerY = PyPlayer(pLoser.getOwner())
		unitY = PyInfo.UnitInfo(pLoser.getUnitType())

		pPlayer = gc.getPlayer(pWinner.getOwner())
		pLPlayer = gc.getPlayer(pLoser.getOwner())

		if (pWinner.getOwner() == gc.getBARBARIAN_PLAYER() or pWinner.isHiddenNationality()):
			pPlot = pLoser.plot()
			if pLoser.getUnitType() == gc.getInfoTypeForString('UNIT_AQUAFORMER'):
				iGold = (gc.getGameSpeedInfo(gc.getGame().getGameSpeedType()).getTrainPercent() * 6) / 5
				pPlayer.changeGold(iGold)
				if (pWinner.getOwner() == gc.getBARBARIAN_PLAYER()):
					pLPlayer.initUnit(gc.getInfoTypeForString('UNIT_AQUAFORMER_DAMAGED'), pPlot.getX(), pPlot.getY(), UnitAITypes.NO_UNITAI, DirectionTypes.DIRECTION_NORTH)
			elif pLoser.getUnitType() == gc.getInfoTypeForString('UNIT_FORMER'):
				iGold = (gc.getGameSpeedInfo(gc.getGame().getGameSpeedType()).getTrainPercent() * 6) / 5
				pPlayer.changeGold(iGold)
				if (pWinner.getOwner() == gc.getBARBARIAN_PLAYER()):
					pLPlayer.initUnit(gc.getInfoTypeForString('UNIT_FORMER_DAMAGED'), pPlot.getX(), pPlot.getY(), UnitAITypes.NO_UNITAI, DirectionTypes.DIRECTION_NORTH)

	def onImprovementBuilt(self, argsList):
		'Improvement Built'
		self.parent.onImprovementBuilt(self, argsList)
		iImprovement, iX, iY = argsList

		pPlot = CyMap().plot(iX,iY)

		iBunkerID = CvUtil.findInfoTypeNum(gc.getUnitInfo,gc.getNumUnitInfos(),'UNIT_BUNKER')
		
		if iImprovement == gc.getInfoTypeForString('IMPROVEMENT_BUNKER'):
			pPlot.setRouteType(gc.getInfoTypeForString('ROUTE_ROAD'))
			if pPlot.getOwner() != -1:
				pPlayer = gc.getPlayer(pPlot.getOwner())
				pUnit = pPlayer.initUnit(iBunkerID, iX, iY, UnitAITypes.UNITAI_IMMOBILE, DirectionTypes.NO_DIRECTION)
				if pPlayer.countNumBuildings(gc.getInfoTypeForString('BUILDING_HUNTER-SEEKER_ALGORITHM')) > 0:
					pUnit.setHasPromotion(gc.getInfoTypeForString('PROMOTION_HUNTER-SEEKER_ALGORITHM'), True)

	def onBuildingBuilt(self, argsList):
		'Building Completed'
		self.parent.onBuildingBuilt(self, argsList)
		pCity, iBuildingType = argsList
		game = gc.getGame()
		
		player = pCity.getOwner()
		pPlayer = gc.getPlayer(player)
		pPlot = pCity.plot()
		
		if iBuildingType == gc.getInfoTypeForString('BUILDING_PERIMETER_DEFENSE'):
			pUnit = pPlayer.initUnit(gc.getInfoTypeForString('UNIT_BUNKER'), pCity.getX(), pCity.getY(), UnitAITypes.UNITAI_IMMOBILE, DirectionTypes.DIRECTION_NORTH)
			pPlot.setRouteType(gc.getInfoTypeForString('ROUTE_ROAD'))
			if pPlayer.countNumBuildings(gc.getInfoTypeForString('BUILDING_HUNTER-SEEKER_ALGORITHM')) > 0:
				pUnit.setHasPromotion(gc.getInfoTypeForString('PROMOTION_HUNTER-SEEKER_ALGORITHM'), True)
		elif iBuildingType == gc.getInfoTypeForString('BUILDING_SOLAR_POWER_TRANSMITTER'):
			pPlayer.initUnit(gc.getInfoTypeForString('UNIT_SOLAR_POWER_TRANSMITTER'), pCity.getX(), pCity.getY(), UnitAITypes.UNITAI_IMMOBILE, DirectionTypes.DIRECTION_NORTH)
		elif iBuildingType == gc.getInfoTypeForString('BUILDING_DAWN_OF_PLANET'):
			pCity.setName(CyTranslator().getText("TXT_KEY_BUILDING_DAWN_OF_PLANET",()), False)
			bStillAlive = False
			for iPlayer in range(gc.getMAX_PLAYERS()):
				pCultPlayer = gc.getPlayer(iPlayer)
				if pCultPlayer.isAlive():
					if pCultPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_CULT'):
						iCultPlayer = iPlayer
						bStillAlive = True
						break
			if bStillAlive: # if (pCultPlayer != NO_PLAYER) in python??
				pCultPlayer.initUnit(gc.getInfoTypeForString('UNIT_FUNGAL_TOWER'), pPlot.getX(), pPlot.getY(), UnitAITypes.UNITAI_IMMOBILE, DirectionTypes.DIRECTION_NORTH)
				pCultPlayer.initUnit(gc.getInfoTypeForString('UNIT_LOCUST'), pPlot.getX(), pPlot.getY(), UnitAITypes.UNITAI_ATTACK, DirectionTypes.DIRECTION_NORTH)
				if pPlayer.isHuman():
					popupInfo = CyPopupInfo()
					popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
					popupInfo.setText(CyTranslator().getText("TXT_KEY_POPUP_CONTROL_CULT",()))
					popupInfo.setData1(player)
					popupInfo.setData2(iCultPlayer)
					popupInfo.addPythonButton(CyTranslator().getText("TXT_KEY_POPUP_YES", ()), "")
					popupInfo.addPythonButton(CyTranslator().getText("TXT_KEY_POPUP_NO", ()), "")
					popupInfo.setOnClickedPythonCallback("reassignPlayer")
					popupInfo.addPopup(player)
		elif not pCity.isCapital():
			if pPlayer.countNumBuildings(iBuildingType) == 1:
				if iBuildingType == gc.getInfoTypeForString('BUILDING_MORGAN_DATA_SYSTEMS'):
					pCity.setName(CyTranslator().getText("TXT_KEY_CITY_NAME_MORGAN_DATA_SYSTEMS",()), False)
				elif iBuildingType == gc.getInfoTypeForString('BUILDING_MORGAN_METAGENICS'):
					pCity.setName(CyTranslator().getText("TXT_KEY_CITY_NAME_MORGAN_METAGENICS",()), False)
				elif iBuildingType == gc.getInfoTypeForString('BUILDING_MORGAN_MINES'):
					pCity.setName(CyTranslator().getText("TXT_KEY_CITY_NAME_MORGAN_MINES",()), False)
				elif iBuildingType == gc.getInfoTypeForString('BUILDING_MORGAN_SOLARFEX'):
					pCity.setName(CyTranslator().getText("TXT_KEY_CITY_NAME_MORGAN_SOLARFEX",()), False)
				elif iBuildingType == gc.getInfoTypeForString('BUILDING_MORGAN_AERODYNAMICS'):
					pCity.setName(CyTranslator().getText("TXT_KEY_CITY_NAME_MORGAN_AERODYNAMICS",()), False)

	def onUnitCreated(self, argsList):
		'Unit Completed'
		self.parent.onUnitCreated(self, argsList)
		unit = argsList[0]
		player = PyPlayer(unit.getOwner())

		pPlayer = gc.getPlayer(unit.getOwner())
		
		#iPromotionLight = gc.getInfoTypeForString('PROMOTION_LIGHT')
		
		#if pPlayer.hasTrait(gc.getInfoTypeForString('TRAIT_DESPOT')):
		#	if unit.getUnitCombatType() == gc.getInfoTypeForString('UNITCOMBAT_INFANTRY') or unit.getUnitCombatType() == gc.getInfoTypeForString('UNITCOMBAT_FLAMETHROWER'):
		#		if 2 == CyGame().getSorenRandNum(2, "Maniac"):
		#			unit.setHasPromotion(iPromotionLight, True)
	
	def onUnitBuilt(self, argsList):
		'Unit Completed'
		self.parent.onUnitBuilt(self, argsList)
		city = argsList[0]
		unit = argsList[1]
		player = PyPlayer(city.getOwner())
		
		pPlayer = gc.getPlayer(unit.getOwner())
		
		iPromotionLight = gc.getInfoTypeForString('PROMOTION_LIGHT')
		
		if pPlayer.hasTrait(gc.getInfoTypeForString('TRAIT_DESPOT')):
			if unit.getUnitCombatType() == gc.getInfoTypeForString('UNITCOMBAT_INFANTRY') or unit.getUnitCombatType() == gc.getInfoTypeForString('UNITCOMBAT_FLAMETHROWER'):
				if 0 == CyGame().getSorenRandNum(2, "Maniac"):
					unit.setHasPromotion(iPromotionLight, True)
		elif pPlayer.hasTrait(gc.getInfoTypeForString('TRAIT_ECOLOGIST')):
			if unit.getUnitType() == gc.getInfoTypeForString('UNIT_COLONY_POD') or unit.getUnitType() == gc.getInfoTypeForString('UNIT_PROBE_TEAM'):
				unit.setHasPromotion(gc.getInfoTypeForString('PROMOTION_FUNGUS'), True)
				unit.setHasPromotion(gc.getInfoTypeForString('PROMOTION_FOREST_CAMOUFLAGE3'), True)

	def onUnitKilled(self, argsList):
		'Unit Killed'
		self.parent.onUnitKilled(self, argsList)
		unit, iAttacker = argsList
		player = PyPlayer(unit.getOwner())
		attacker = PyPlayer(iAttacker)

		pAttacker = gc.getPlayer(iAttacker)
		iPlayer = unit.getOwner()
		pPlayer = gc.getPlayer(iPlayer)
		pPlot = unit.plot()

		if (iAttacker == gc.getBARBARIAN_PLAYER()):
			if unit.getUnitType() == gc.getInfoTypeForString('UNIT_AQUAFORMER'):
				iGold = (gc.getGameSpeedInfo(gc.getGame().getGameSpeedType()).getTrainPercent() * 6) / 5
				pAttacker.changeGold(iGold)
				newUnit = pPlayer.initUnit(gc.getInfoTypeForString('UNIT_AQUAFORMER_DAMAGED'), pPlot.getX(), pPlot.getY(), UnitAITypes.NO_UNITAI, DirectionTypes.DIRECTION_NORTH)
			elif unit.getUnitType() == gc.getInfoTypeForString('UNIT_FORMER'):
				iGold = (gc.getGameSpeedInfo(gc.getGame().getGameSpeedType()).getTrainPercent() * 6) / 5
				pAttacker.changeGold(iGold)
				newUnit = pPlayer.initUnit(gc.getInfoTypeForString('UNIT_FORMER_DAMAGED'), pPlot.getX(), pPlot.getY(), UnitAITypes.NO_UNITAI, DirectionTypes.DIRECTION_NORTH)
		if unit.getUnitType() == gc.getInfoTypeForString('UNIT_BUNKER') or unit.getUnitType() == gc.getInfoTypeForString('UNIT_BUNKER2') or unit.getUnitType() == gc.getInfoTypeForString('UNIT_BUNKER3'):
			if pPlot.getImprovementType() == gc.getInfoTypeForString('IMPROVEMENT_BUNKER'):
				if not pPlot.isCity():
					pPlot.setRouteType(-1)
				pPlot.setImprovementType(-1)
			if pPlot.isCity():
				pCity = pPlot.getPlotCity()
				pCity.setNumRealBuilding(gc.getInfoTypeForString('BUILDING_PERIMETER_DEFENSE'), 0)
		elif unit.getUnitType() == gc.getInfoTypeForString('UNIT_SOLAR_POWER_TRANSMITTER'):
			if pPlot.isCity():
				pCity = pPlot.getPlotCity()
				pCity.setNumRealBuilding(gc.getInfoTypeForString('BUILDING_SOLAR_POWER_TRANSMITTER'), 0)

	def onTechAcquired(self, argsList):
		'Tech Acquired'
		self.parent.onTechAcquired(self, argsList)
		iTechType, iTeam, iPlayer, bAnnounce = argsList

		pPlayer = gc.getPlayer(iPlayer)
		pCapitalCity = pPlayer.getCapitalCity()
		iLeviathan = CvUtil.findInfoTypeNum(gc.getUnitInfo,gc.getNumUnitInfos(),"UNIT_LEVIATHAN")

		if pPlayer.getCurrentEra() == gc.getInfoTypeForString('ERA_EXPANSION') or pPlayer.getCurrentEra() == gc.getInfoTypeForString('ERA_CROSSFIRE'):
			if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_BELIEVERS'):
				pPlayer.setCurrentEra(gc.getInfoTypeForString('ERA_BELIEVERS'))
			elif pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_GAIANS'):
				pPlayer.setCurrentEra(gc.getInfoTypeForString('ERA_GAIANS'))
			elif pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_HIVE'):
				pPlayer.setCurrentEra(gc.getInfoTypeForString('ERA_HIVE'))
			elif pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_MORGANITES'):
				pPlayer.setCurrentEra(gc.getInfoTypeForString('ERA_MORGANITES'))
			elif pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_PEACEKEEPERS'):
				pPlayer.setCurrentEra(gc.getInfoTypeForString('ERA_PEACEKEEPERS'))
			elif pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_SPARTANS'):
				pPlayer.setCurrentEra(gc.getInfoTypeForString('ERA_SPARTANS'))
			elif pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_UNIVERSITY'):
				pPlayer.setCurrentEra(gc.getInfoTypeForString('ERA_UNIVERSITY'))
			elif pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_ANGELS'):
				pPlayer.setCurrentEra(gc.getInfoTypeForString('ERA_ANGELS'))
			elif pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_CONSCIOUSNESS'):
				pPlayer.setCurrentEra(gc.getInfoTypeForString('ERA_CONSCIOUSNESS'))
			elif pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_DRONES'):
				pPlayer.setCurrentEra(gc.getInfoTypeForString('ERA_DRONES'))
			elif pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_PIRATES'):
				pPlayer.setCurrentEra(gc.getInfoTypeForString('ERA_PIRATES'))
			elif pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_CULT'):
				pPlayer.setCurrentEra(gc.getInfoTypeForString('ERA_CULT'))

		if pCapitalCity != -1:
			if iTechType == CvUtil.findInfoTypeNum(gc.getTechInfo,gc.getNumTechInfos(),"TECH_NEUTRONIUM"):
				gc.getPlayer(iPlayer).initUnit(iLeviathan, pCapitalCity.getX(), pCapitalCity.getY(), UnitAITypes.UNITAI_ATTACK, DirectionTypes.NO_DIRECTION)
			elif iTechType == CvUtil.findInfoTypeNum(gc.getTechInfo,gc.getNumTechInfos(),"TECH_INFORMATION_NETWORKS"):
				if gc.getGame().getStartEra() == gc.getInfoTypeForString('ERA_ARRIVAL'):
					pCapitalCity.setNumRealBuilding(gc.getInfoTypeForString('BUILDING_NETWORK_NODE'), 1)
				

	def onCityBuilt(self, argsList):
		'City Built'
		self.parent.onCityBuilt(self, argsList)
		city = argsList[0]

		pPlot = city.plot()
		pPlayer = gc.getPlayer(city.getOwner())
		pTeam = gc.getTeam(pPlayer.getTeam())
		pCapitalCity = pPlayer.getCapitalCity()
		pStartEra = gc.getGame().getStartEra()
		iRockyPolar = gc.getInfoTypeForString('TERRAIN_ROCKY_POLAR')
		iRockyArid = gc.getInfoTypeForString('TERRAIN_ROCKY_ARID')
		iRockyMoist = gc.getInfoTypeForString('TERRAIN_ROCKY_MOIST')
		iRockyRainy = gc.getInfoTypeForString('TERRAIN_ROCKY_RAINY')
		iFlatPolar = gc.getInfoTypeForString('TERRAIN_FLAT_POLAR')
		iFlatArid = gc.getInfoTypeForString('TERRAIN_FLAT_ARID')
		iFlatMoist = gc.getInfoTypeForString('TERRAIN_FLAT_MOIST')
		iFlatRainy = gc.getInfoTypeForString('TERRAIN_FLAT_RAINY')
		iHive = gc.getInfoTypeForString('CIVILIZATION_HIVE')

		if pPlot.isWater():
			city.setNumRealBuilding(gc.getInfoTypeForString('BUILDING_SEA_BASE'), 1)
			if pPlayer.isHuman() == False:
				pPlayer.initUnit(gc.getInfoTypeForString('UNIT_SCOUT_PATROL'), city.getX(), city.getY(), UnitAITypes.UNITAI_CITY_DEFENSE, DirectionTypes.NO_DIRECTION)
		elif pPlayer.getCivilizationType() != iHive:
			if pPlot.getTerrainType() == iRockyMoist:
				pPlot.setTerrainType(iFlatMoist,True,True)
			elif pPlot.getTerrainType() == iRockyRainy:
				pPlot.setTerrainType(iFlatRainy,True,True)
			elif pPlot.getTerrainType() == iRockyArid:
				pPlot.setTerrainType(iFlatArid,True,True)
			elif pPlot.getTerrainType() == iRockyPolar:
				pPlot.setTerrainType(iFlatPolar,True,True)
		if pTeam.isHasTech(gc.getInfoTypeForString('TECH_MAGNETIC_PROPULSION')):
			pPlot.setRouteType(gc.getInfoTypeForString('ROUTE_ROAD'))
		if pPlayer.getNumCities() == 1 and pCapitalCity != -1:
			if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_PIRATES'):
				newUnit = pPlayer.initUnit(gc.getInfoTypeForString('UNIT_BUNKER'), pCapitalCity.getX(), pCapitalCity.getY(), UnitAITypes.UNITAI_IMMOBILE, DirectionTypes.DIRECTION_NORTH)
				newUnit.setHasPromotion(gc.getInfoTypeForString('PROMOTION_NAVAL_FORTRESS'), True)
			if pStartEra == gc.getInfoTypeForString('ERA_ARRIVAL'):
				bStillAlive = False
				for iPlayer in range(gc.getMAX_PLAYERS()):
					pHumanPlayer = gc.getPlayer(iPlayer)
					if pHumanPlayer.isHuman():
						iHumanPlayer = iPlayer
						bStillAlive = True
						break
					break # assuming human player is slot 0. If not, player probably has already switched once
				if pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_ANGELS'):
					pPlayer.initUnit(gc.getInfoTypeForString('UNIT_BUNKER'), pCapitalCity.getX(), pCapitalCity.getY(), UnitAITypes.UNITAI_IMMOBILE, DirectionTypes.DIRECTION_NORTH)
					pPlot.setRouteType(gc.getInfoTypeForString('ROUTE_ROAD'))
					pPlayer.initUnit(gc.getInfoTypeForString('UNIT_DATAJACK'), pCapitalCity.getX(), pCapitalCity.getY(), UnitAITypes.UNITAI_MERCHANT, DirectionTypes.DIRECTION_NORTH)
					pCapitalCity.setNumRealBuilding(gc.getInfoTypeForString('BUILDING_NETWORK_NODE'), 1)
					if pPlot.getBonusType(-1) == -1:
						iMod = CyGame().getSorenRandNum(2, "Maniac")
						if iMod != 0:
							pPlot.setBonusType(gc.getInfoTypeForString('BONUS_MINERAL'))
						else:
							pPlot.setBonusType(gc.getInfoTypeForString('BONUS_NUTRIENT'))
					if bStillAlive: # if (pHumanPlayer != NO_PLAYER) in python??
						popupInfo = CyPopupInfo()
						popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
						popupInfo.setText(CyTranslator().getText("TXT_KEY_POPUP_CONTROL_ANGELS",()))
						popupInfo.setData1(iHumanPlayer)
						popupInfo.setData2(city.getOwner())
						popupInfo.addPythonButton(CyTranslator().getText("TXT_KEY_POPUP_YES", ()), "")
						popupInfo.addPythonButton(CyTranslator().getText("TXT_KEY_POPUP_NO", ()), "")
						popupInfo.setOnClickedPythonCallback("reassignPlayer")
						popupInfo.addPopup(iHumanPlayer)
				elif pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_CONSCIOUSNESS'):
					pPlayer.initUnit(gc.getInfoTypeForString('UNIT_BUNKER'), pCapitalCity.getX(), pCapitalCity.getY(), UnitAITypes.UNITAI_IMMOBILE, DirectionTypes.DIRECTION_NORTH)
					pPlot.setRouteType(gc.getInfoTypeForString('ROUTE_ROAD'))
					pPlayer.initUnit(gc.getInfoTypeForString('UNIT_SCIENTIST'), pCapitalCity.getX(), pCapitalCity.getY(), UnitAITypes.UNITAI_SCIENTIST, DirectionTypes.DIRECTION_NORTH)
					pCapitalCity.setNumRealBuilding(gc.getInfoTypeForString('BUILDING_NETWORK_NODE'), 1)
					pCapitalCity.setNumRealBuilding(gc.getInfoTypeForString('BUILDING_CYBERCORE'), 1)
					if pPlot.getBonusType(-1) == -1:
						iMod = CyGame().getSorenRandNum(2, "Maniac")
						if iMod != 0:
							pPlot.setBonusType(gc.getInfoTypeForString('BONUS_MINERAL'))
						else:
							pPlot.setBonusType(gc.getInfoTypeForString('BONUS_NUTRIENT'))
					if bStillAlive: # if (pHumanPlayer != NO_PLAYER) in python??
						popupInfo = CyPopupInfo()
						popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
						popupInfo.setText(CyTranslator().getText("TXT_KEY_POPUP_CONTROL_CONSCIOUSNESS",()))
						popupInfo.setData1(iHumanPlayer)
						popupInfo.setData2(city.getOwner())
						popupInfo.addPythonButton(CyTranslator().getText("TXT_KEY_POPUP_YES", ()), "")
						popupInfo.addPythonButton(CyTranslator().getText("TXT_KEY_POPUP_NO", ()), "")
						popupInfo.setOnClickedPythonCallback("reassignPlayer")
						popupInfo.addPopup(iHumanPlayer)
				elif pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_DRONES'):
					pPlayer.initUnit(gc.getInfoTypeForString('UNIT_BUNKER'), pCapitalCity.getX(), pCapitalCity.getY(), UnitAITypes.UNITAI_IMMOBILE, DirectionTypes.DIRECTION_NORTH)
					pPlot.setRouteType(gc.getInfoTypeForString('ROUTE_ROAD'))
					#pPlayer.initUnit(gc.getInfoTypeForString('UNIT_ENGINEER'), pCapitalCity.getX(), pCapitalCity.getY(), UnitAITypes.UNITAI_ENGINEER, DirectionTypes.DIRECTION_NORTH)
					city.changeFreeSpecialistCount(gc.getInfoTypeForString('SPECIALIST_GREAT_ENGINEER'), 1)
					pCapitalCity.setNumRealBuilding(gc.getInfoTypeForString('BUILDING_NETWORK_NODE'), 1)
					if pPlot.getBonusType(-1) == -1:
						iMod = CyGame().getSorenRandNum(2, "Maniac")
						if iMod != 0:
							pPlot.setBonusType(gc.getInfoTypeForString('BONUS_MINERAL'))
						else:
							pPlot.setBonusType(gc.getInfoTypeForString('BONUS_NUTRIENT'))
					if bStillAlive: # if (pHumanPlayer != NO_PLAYER) in python?? isNone() ?
						popupInfo = CyPopupInfo()
						popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
						popupInfo.setText(CyTranslator().getText("TXT_KEY_POPUP_CONTROL_DRONES",()))
						popupInfo.setData1(iHumanPlayer)
						popupInfo.setData2(city.getOwner())
						popupInfo.addPythonButton(CyTranslator().getText("TXT_KEY_POPUP_YES", ()), "")
						popupInfo.addPythonButton(CyTranslator().getText("TXT_KEY_POPUP_NO", ()), "")
						popupInfo.setOnClickedPythonCallback("reassignPlayer")
						popupInfo.addPopup(iHumanPlayer)
				elif pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_PIRATES'):
					pPlayer.initUnit(gc.getInfoTypeForString('UNIT_GENERAL'), pCapitalCity.getX(), pCapitalCity.getY(), UnitAITypes.UNITAI_GENERAL, DirectionTypes.DIRECTION_NORTH)
					pCapitalCity.setNumRealBuilding(gc.getInfoTypeForString('BUILDING_NETWORK_NODE'), 1)
					if pPlot.getBonusType(-1) == -1:
						iMod = CyGame().getSorenRandNum(2, "Maniac")
						if iMod != 0:
							pPlot.setBonusType(gc.getInfoTypeForString('BONUS_MINERAL'))
						else:
							pPlot.setBonusType(gc.getInfoTypeForString('BONUS_NUTRIENT'))
					if bStillAlive: # if (pHumanPlayer != NO_PLAYER) in python??
						popupInfo = CyPopupInfo()
						popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON)
						popupInfo.setText(CyTranslator().getText("TXT_KEY_POPUP_CONTROL_PIRATES",()))
						popupInfo.setData1(iHumanPlayer)
						popupInfo.setData2(city.getOwner())
						popupInfo.addPythonButton(CyTranslator().getText("TXT_KEY_POPUP_YES", ()), "")
						popupInfo.addPythonButton(CyTranslator().getText("TXT_KEY_POPUP_NO", ()), "")
						popupInfo.setOnClickedPythonCallback("reassignPlayer")
						popupInfo.addPopup(iHumanPlayer)
				elif pPlayer.getCivilizationType() == gc.getInfoTypeForString('CIVILIZATION_UNIVERSITY'):
					pCapitalCity.setNumRealBuilding(gc.getInfoTypeForString('BUILDING_NETWORK_NODE'), 1)

		if city.getOwner() == CyGame().getActivePlayer():
			if pPlayer.getCivilizationType() == iHive:
				CyInterface().playGeneralSound("AS2D_HIVE_BASEFOUND_THEME")
				
	def onCityAcquiredAndKept(self, argsList):
		'City Acquired and Kept'
		self.parent.onCityAcquiredAndKept(self, argsList)
		iOwner,pCity = argsList
		
		pPlayer = gc.getPlayer(iOwner)
		pTeam = gc.getTeam(pPlayer.getTeam())
		pPlot = pCity.plot()
		
		if pTeam.isHasTech(gc.getInfoTypeForString('TECH_MAGNETIC_PROPULSION')):
			pPlot.setRouteType(gc.getInfoTypeForString('ROUTE_ROAD'))

	def onCityDoTurn(self, argsList):
		'City Production'
		self.parent.onCityDoTurn(self, argsList)
		pCity = argsList[0]
		iPlayer = argsList[1]

		pPlot = pCity.plot()
		pPlayer = gc.getPlayer(iPlayer)
		infoCiv = gc.getCivilizationInfo(pPlayer.getCivilizationType())
		iInfestation = infoCiv.getCivilizationBuildings(gc.getInfoTypeForString('BUILDINGCLASS_INFESTATION'))
		iStronghold = infoCiv.getCivilizationBuildings(gc.getInfoTypeForString('BUILDINGCLASS_REBEL_STRONGHOLD'))
		iSolarPowerTransmitter = gc.getInfoTypeForString('UNIT_SOLAR_POWER_TRANSMITTER')
		iPartisan = gc.getInfoTypeForString('UNIT_PARTISAN')
		bKeep = 0
		
		if iPlayer == gc.getBARBARIAN_PLAYER():
			if (pCity.getNumRealBuilding(iInfestation) > 0):
				if pCity.getPopulation() > 1:
					iChance = CyGame().getSorenRandNum(100, "Maniac")
					if iChance < 15:
						if pCity.getPopulation() > 2:
							pCity.changePopulation(-2)
							pPlayer.initUnit(gc.getInfoTypeForString('UNIT_FUNGAL_TOWER'), pCity.getX(), pCity.getY(), UnitAITypes.UNITAI_IMMOBILE, DirectionTypes.NO_DIRECTION)
					elif iChance < 25:
						pCity.changePopulation(-1)
						pPlayer.initUnit(gc.getInfoTypeForString('UNIT_SPORE_LAUNCHER'), pCity.getX(), pCity.getY(), UnitAITypes.UNITAI_CITY_DEFENSE, DirectionTypes.NO_DIRECTION)
					elif iChance < 50:
						pCity.changePopulation(-1)
						pPlayer.initUnit(gc.getInfoTypeForString('UNIT_MIND_WORM'), pCity.getX(), pCity.getY(), UnitAITypes.UNITAI_CITY_DEFENSE, DirectionTypes.NO_DIRECTION)
		for i in range(pPlot.getNumUnits()):
			pUnit = pPlot.getUnit(i)
			if pUnit.getUnitType() == iSolarPowerTransmitter:
				bKeep = 1
			elif iPlayer == gc.getBARBARIAN_PLAYER():
				if (pCity.getNumRealBuilding(iInfestation) == 0 and pCity.getNumRealBuilding(iStronghold) == 0):
					if pUnit.getUnitType() == iPartisan:
						pCity.setNumRealBuilding(iStronghold, 1)
					elif pPlot.getUnit(i).isPsi():
						pCity.setNumRealBuilding(iInfestation, 1)
				break
		pCity.setNumRealBuilding(gc.getInfoTypeForString('BUILDING_SOLAR_POWER_TRANSMITTER'), bKeep)

	def onGameUpdate(self, argsList):
		'sample generic event, called on each game turn slice'
		self.parent.onGameUpdate(self, argsList)
		genericArgs = argsList[0][0]	# tuple of tuple of my args
		turnSlice = genericArgs[0]

		#OOSLogger.doGameUpdate()
		
		"""
		Checks for active player turn begin/end.
		"""
		eState = CyInterface().getEndTurnState()
		if eState == EndTurnButtonStates.END_TURN_GO:
			"""Fires the BeginActivePlayerTurn event if either the active player or game turn
			have changed since the last check. This signifies that the active player is about
			to be able to move their units.			
			Called by onGameUpdate() when the End Turn Button is green.
			"""
			iTurn = gc.getGame().getGameTurn()
			ePlayer = gc.getGame().getActivePlayer()
			if self.iActiveTurn != iTurn or self.eActivePlayer != ePlayer:
				self.iActiveTurn = iTurn
				self.eActivePlayer = ePlayer
				self.bEndTurnFired = False
				self.onBeginActivePlayerTurn(ePlayer, iTurn)
				#self.fireEvent("BeginActivePlayerTurn", ePlayer, iTurn)
		else:
			"""Fires the endTurnReady event if it hasn't been fired since the active player's turn started.
			Called by onGameUpdate() when the End Turn Button is red.
			"""
			if not self.bEndTurnFired:
				self.bEndTurnFired = True
				#self.fireEvent("endTurnReady", self.iActiveTurn)
				#self.onEndTurnReady(self.iActiveTurn)
				pPlayer = gc.getPlayer(self.eActivePlayer)
				if pPlayer.isHuman():
					CyInterface().playGeneralSound("AS2D_TURN_COMPLETE")				

	def reset(self, argsList=None):
		self.iActiveTurn = -1
		self.eActivePlayer = -1
		self.bEndTurnFired = False
		
		self.PrevAvailTechTrades = {}
		
	def onBeginActivePlayerTurn(self, ePlayer, iGameTurn):
		"""Called when the active player can start their turn."""
		self.CheckForAlerts(ePlayer, PyPlayer(ePlayer).getTeam(), True)
		
	def CheckForAlerts(self, iActivePlayer, activeTeam, bBeginTurn):
	##Added "else: pass" code to diagnose strange results - might be related to indent issues
	
		pActivePlayer = gc.getPlayer(iActivePlayer)
	
		# tech trades
		if (bBeginTurn):
			researchTechs = set()
			for iTech in range(gc.getNumTechInfos()):
				if (pActivePlayer.canResearch(iTech, True)):
					researchTechs.add(iTech)
			techsByPlayer = cf.getTechTrades(pActivePlayer, activeTeam)
			for iLoopPlayer, currentTechs in techsByPlayer.iteritems():

				#Did he have trades avail last turn
				if (self.PrevAvailTechTrades.has_key(iLoopPlayer)):
					previousTechs = self.PrevAvailTechTrades[iLoopPlayer]
				else:
					previousTechs = set()
					
				#Determine new techs
				newTechs = currentTechs.difference(previousTechs).intersection(researchTechs)
				if (newTechs):
					szNewTechs = cf.buildTechString(newTechs)
					message = localText.getText("TXT_KEY_MORECIV4LERTS_NEW_TECH_AVAIL",	
												(gc.getPlayer(iLoopPlayer).getName(), szNewTechs))
					cf.addMessageNoIcon(iActivePlayer, message)
				
				#Determine removed techs
				removedTechs = previousTechs.difference(currentTechs).intersection(researchTechs)
				if (removedTechs):
					szRemovedTechs = cf.buildTechString(removedTechs)
					message = localText.getText("TXT_KEY_MORECIV4LERTS_TECH_NOT_AVAIL",	
												(gc.getPlayer(iLoopPlayer).getName(), szRemovedTechs))
					cf.addMessageNoIcon(iActivePlayer, message)
				
			else: pass #end activePlayer loop

			#save curr trades for next time
			self.PrevAvailTechTrades = techsByPlayer

		else: pass #end new trades if